package com.example.i18n.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

@Configuration
public class LocalLanguageConfig {
    /**
     * 默认解析器 其中locale表示默认语言
     */
    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver acceptHeaderLocaleResolver = new LanguageLocalResolvers();
        return acceptHeaderLocaleResolver;
    }
}


/**
 * 改变语言解析逻辑
 */
class LanguageLocalResolvers extends AcceptHeaderLocaleResolver {
    // 系统支持的语言
    private static final List<Locale> SUPPORTED_LOCALES = Arrays.asList(
            Locale.SIMPLIFIED_CHINESE,  // zh-CN
            Locale.US // en-US
    );

    private static final Locale DEFAULT_LOCALE = Locale.US;

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String headerLang = request.getHeader("Accept-Language");
        if (headerLang == null || headerLang.isEmpty()) {
            return DEFAULT_LOCALE; // 默认中文
        }

        // 解析 Accept-Language，按优先级排序
        List<Locale.LanguageRange> list = Locale.LanguageRange.parse(headerLang);

        // 匹配支持的语言
        Locale locale = Locale.lookup(list, SUPPORTED_LOCALES);
        return locale != null ? locale : DEFAULT_LOCALE;
    }
}